package com.hamll.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hamll.common.dto.PageDTO;
import com.hamll.item.mapper.ItemMapper;
import com.hamll.item.pojo.Item;
import com.hamll.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {

    @Autowired
    private ItemService itemService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageDTO<Item> pageItem(Integer page, Integer size) {

        Page<Item> itemPage = new Page<>(page, size);
        LambdaQueryWrapper<Item> wrapper = new LambdaQueryWrapper<>();
        //ne不等于
        wrapper.ne(Item::getStatus,3);
        //倒序
        wrapper.orderByDesc(Item::getId);
        Page<Item> page1 = itemService.page(itemPage,wrapper);
        PageDTO<Item> dto = new PageDTO<>(page1.getTotal(), page1.getRecords());
        return dto;
    }

    @Override
    public Item queryItemById(Long id) {

        Item item = itemService.getById(id);
        return item;
    }

    @Override
    public void addItem(Item item) {
        if (StringUtils.isEmpty(item.getName())){
            throw new RuntimeException("名称为空！");
        }

        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        item.setStatus(1);

        itemService.save(item);
    }

    @Override
    public void upOrDownItem(Long id, Integer status) {

        Item item = new Item();
        item.setId(id);
        item.setStatus(status);
        item.setUpdateTime(new Date());
        itemService.updateById(item);
        //指定routingkey
        String  routingkey = status==1?"item.up":"item.down";
        //发送消息
        rabbitTemplate.convertAndSend("item.topic",routingkey,id.toString());
    }

    @Override
    public void updateItem(Item item) {
        //状态不能改(之前没有考虑,下回注意)
        item.setStatus(null);
        item.setUpdateTime(new Date());
        itemService.updateById(item);
    }


    //根据id删除商品信息
    //逻辑删除,就是更新状态字段
    @Override
    public void deleteItemById(Long id) {
        //3是删除
        Item item = new Item();
        item.setStatus(3);
        item.setId(id);
        item.setUpdateTime(new Date());
        itemService.updateById(item);
    }

    @Override
    public void deductStock(Long itemId, Integer num) {
        try {
            getBaseMapper().deductStock(itemId, num);
        } catch (Exception e) {
            throw new RuntimeException("库存不足！");
        }
    }

}
